package com.zhongc.advance.web.controller;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zhongc.advance.api.UserService;
import com.zhongc.advance.common.Constant;
import com.zhongc.advance.common.code.CheckCode;
import com.zhongc.advance.common.result.Result;
import com.zhongc.advance.common.result.Status;
import com.zhongc.advance.common.util.BeanUtils;
import com.zhongc.advance.common.util.IPUtil;
import com.zhongc.advance.info.User;
import com.zhongc.advance.order.LoginOrder;
import com.zhongc.advance.order.UserOrder;

@Controller
public class UserController {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
	private UserService userService;
		
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(String userName, String pwd, String loginFrom,
			Model model, HttpServletRequest request, HttpSession session,String yzCode) {
		logger.info("登陆入参");
		Map<String,Object> map =CheckCode.checkCheckcode(session, yzCode);
		if (!(boolean)map.get("code")) {
			model.addAttribute("message", map.get("message"));
			return "/com/login.vm";
		}
		LoginOrder order = new LoginOrder();
		order.setUserName(userName);
		order.setPassWord(pwd);
		order.setLoginFrom(loginFrom);
		order.setIp(IPUtil.getIpAddr(request));
		Result result = userService.login(order);
		if (result.getStatus() != Status.SUCCESS) {
			model.addAttribute("message", result.getDescription());
			model.addAttribute("code", result.getCode());
			return "/com/login.vm";
		}
		model.addAttribute("user", (User)result.getObj());
		session.setAttribute(Constant.Session.SESSION_USER_NAME, userName);
		return "/home";

	}

	@RequestMapping(value = "user/register", method = RequestMethod.POST)
	public String register(Model model, HttpSession session, User user,
			String checkCode, HttpServletRequest request) {
		logger.info("进入 user/register Controller  调用 会员注册接口入参  User->{}", user);
		Map<String, Object> map = CheckCode.checkCheckcode(session, checkCode);
		user.setRegistTime(new Date());
		model.addAttribute("codeMessage", map.get("message"));
		UserOrder order = BeanUtils.copyProperties(user, UserOrder.class);
		order.setUserId("201507089912");
		if (!(Boolean) map.get("code")) {
			return "user/register.vm";
		}
		Result result = userService.register(order);
		return "";

	}
}
